<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="order-page">
    <!-- 订单列表区域 -->
    <div class="order-content">
      <van-tabs v-model:active="active" swipeable>
        <van-tab title="全部" name="all">
          <nothing v-if="orderStore.allOrderListCount === 0"></nothing>
          <div class="order-list" v-else>
            <van-list
              v-model:loading="loadingStates.all"
              :finished="finishedStates.all"
              finished-text="没有更多了"
              @load="onLoadForAll"
              class="order-list"
            >
              <order-list-item 
                v-for="item in orderList.allOrderList"
                :key="item.id"
                :data="item"
                :type="'all'"
                @confirm-change="(data) => handleConfirmChange(data, 'all')"
              />
            </van-list>
          </div>
        </van-tab>
        <van-tab title="待支付" name="pending">
          <nothing v-if="orderStore.pendingPaymentListCount === 0"></nothing>
          <div class="order-list" v-else>
            <van-list
              v-model:loading="loadingStates.pending"
              :finished="finishedStates.pending"
              finished-text="没有更多了"
              @load="onLoadForPendingPayment"
              class="order-list"
            >
              <order-list-item 
                v-for="item in orderList.pendingPaymentList"
                :key="item.id"
                :data="item"
                :type="'pending'"
                @confirm-change="(data) => handleConfirmChange(data, 'pending')"
              />
            </van-list>
          </div>
        </van-tab>
        <van-tab title="已支付" name="paid">
          <nothing v-if="orderStore.finishedOrderListCount === 0"></nothing>
          <div class="order-list" v-else>
            <van-list
              v-model:loading="loadingStates.finished"
              :finished="finishedStates.finished"
              finished-text="没有更多了"
              @load="onLoadForFinished"
              class="order-list"
            >
              <order-list-item 
                v-for="item in orderList.finishedOrderList"
                :key="item.id"
                :data="item"
                :type="'finished'"
                @confirm-change="(data) => handleConfirmChange(data, 'finished')"
              />
            </van-list>
          </div>
        </van-tab>
      </van-tabs>
    </div>

    <!-- 底部操作栏 -->
    <div class="order-footer">
      <van-submit-bar 
        :price="confirmedTotalPrice" 
        :button-text="submitButtonText" 
        @submit="onSubmit"
        :disabled="isSubmitDisabled"
        class="submit-bar"
      >
        <template #default>
          <div class="submit-bar-content">
            <!-- 全选框 -->
            <van-checkbox 
              v-model="isAllChecked" 
              checked-color="#ee0a24"
              @change="handleSelectAllChange"
              :disabled="currentOrderList.length === 0"
              class="select-all-checkbox"
            >
              全选
            </van-checkbox>
            <div class="delete-section" @click="handleDelete">
              <van-icon name="delete" class="delete-icon" />
              <span class="delete-text">删除</span>
            </div>
          </div>
        </template>
        <template #tip>
          <div class="submit-tip">
            <van-icon name="info-o" class="tip-icon" />
            <span class="tip-text">健康的饮食，健康的生活</span>
          </div>
        </template>
      </van-submit-bar>
    </div>
  </div>
</template>

<script setup>
defineOptions({
  name: "OrderIndex",
});
import OrderListItem from "../../components/OrderListItem.vue";
import Nothing from "../../components/Nothing.vue";
import { useOrderStore } from "../../store/order";
import { reactive, ref, computed, watch, onMounted } from "vue";
import { showToast, showConfirmDialog } from "vant";
import router from "../../router";
import { useRoute } from "vue-router";

const orderStore = useOrderStore();
const route = useRoute();
const active = ref("all");
const isAllChecked = ref(false);

// 为每个标签页单独设置加载状态
const loadingStates = reactive({
  all: false,
  pending: false,
  finished: false
});

const finishedStates = reactive({
  all: false,
  pending: false,
  finished: false
});

const orderList = reactive({
  allOrderList: [],
  pendingPaymentList: [],
  finishedOrderList: [],
});

// 获取当前激活标签的订单列表
const currentOrderList = computed(() => {
  switch (active.value) {
    case 'all':
      return orderList.allOrderList;
    case 'pending':
      return orderList.pendingPaymentList;
    case 'paid':
      return orderList.finishedOrderList;
    default:
      return [];
  }
});

// 获取已确认的订单
const confirmedOrders = computed(() => {
  return currentOrderList.value.filter(item => item.isConfirmed);
});

// 检查选中的订单是否包含已支付的订单
const hasPaidOrders = computed(() => {
  return confirmedOrders.value.some(item => item.isPaid === true);
});

// 检查选中的订单是否全部是已支付的订单
const allPaidOrders = computed(() => {
  return confirmedOrders.value.length > 0 && confirmedOrders.value.every(item => item.isPaid === true);
});

// 计算已确认订单的总价（单位：分）
const confirmedTotalPrice = computed(() => {
  return confirmedOrders.value.reduce((total, item) => {
    return total + (item.price * item.num);
  }, 0) * 100;
});

// 提交按钮文本
const submitButtonText = computed(() => {
  if (allPaidOrders.value) {
    return '已支付';
  } else if (hasPaidOrders.value) {
    return '包含已支付订单';
  } else {
    return '提交订单';
  }
});

// 提交按钮是否禁用
const isSubmitDisabled = computed(() => {
  return confirmedOrders.value.length === 0 || hasPaidOrders.value;
});

// 监听路由查询参数，设置激活的tab
watch(() => route.query.tab, (newTab) => {
  if (newTab && ['all', 'pending', 'paid'].includes(newTab)) {
    active.value = newTab;
  }
}, { immediate: true });

// 监听当前订单列表变化，更新全选状态
watch(() => currentOrderList.value, () => {
  if (currentOrderList.value.length === 0) {
    isAllChecked.value = false;
  } else {
    isAllChecked.value = currentOrderList.value.every(item => item.isConfirmed);
  }
}, { immediate: true, deep: true });

// 监听已确认订单数量变化，实时更新全选状态
watch(() => confirmedOrders.value.length, () => {
  if (currentOrderList.value.length === 0) {
    isAllChecked.value = false;
  } else {
    isAllChecked.value = currentOrderList.value.every(item => item.isConfirmed);
  }
});

const onLoadForAll = () => {
  loadingStates.all = true;
  // 模拟异步加载
  setTimeout(() => {
    orderList.allOrderList = [...orderStore.allOrderList];
    loadingStates.all = false;
    finishedStates.all = true;
  }, 300);
};

const onLoadForPendingPayment = () => {
  loadingStates.pending = true;
  setTimeout(() => {
    orderList.pendingPaymentList = [...orderStore.pendingPaymentList];
    loadingStates.pending = false;
    finishedStates.pending = true;
  }, 300);
};

const onLoadForFinished = () => {
  loadingStates.finished = true;
  setTimeout(() => {
    orderList.finishedOrderList = [...orderStore.finishedOrderList];
    loadingStates.finished = false;
    finishedStates.finished = true;
  }, 300);
};

// 处理订单项选中确认状态变化
const handleConfirmChange = ({ item, isConfirmed }, type) => {
  // 参数验证
  if (!item || !item.id) {
    return;
  }

  // 更新 Pinia 中的订单状态
  orderStore.updateOrderConfirmed(item, isConfirmed);
  
  // 同步更新本地订单列表（确保响应式更新）
  const updateLocalOrder = (orderList) => {
    const index = orderList.findIndex(order => order.id === item.id);
    if (index !== -1) {
      // 直接修改数组项的属性，Vue会自动检测变化
      orderList[index].isConfirmed = isConfirmed;
    }
  };

  // 根据类型更新对应的本地列表
  switch (type) {
    case 'all':
      // 在"全部"列表中更新
      updateLocalOrder(orderList.allOrderList);
      // 同时在对应的分类列表中也更新
      updateLocalOrder(orderList.pendingPaymentList);
      updateLocalOrder(orderList.finishedOrderList);
      break;
    case 'pending': 
      updateLocalOrder(orderList.pendingPaymentList);
      // 同时在"全部"列表中也更新
      updateLocalOrder(orderList.allOrderList);
      break;
    case 'finished':
      updateLocalOrder(orderList.finishedOrderList);
      // 同时在"全部"列表中也更新
      updateLocalOrder(orderList.allOrderList);
      break;
    default:
      break;
  }
};

// 全选状态变化
const handleSelectAllChange = (checked) => {
  // 更新当前标签页的所有订单确认状态
  currentOrderList.value.forEach((item, index) => {
    // 更新本地列表
    currentOrderList.value[index] = { ...item, isConfirmed: checked };
    // 更新 Pinia store
    orderStore.updateOrderConfirmed(item, checked);
  });
};

// 处理删除
const handleDelete = () => {
  const confirmedItems = confirmedOrders.value;
  if (confirmedItems.length === 0) {
    showToast('请先选择要删除的订单');
    return;
  }
  
  showConfirmDialog({
    title: '删除确认',
    message: `确定要删除选中的${confirmedItems.length}个订单吗？`,
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    confirmButtonColor: '#ee0a24'
  })
  .then(() => {
    // 从store中删除已确认的订单
    confirmedItems.forEach(item => {
      orderStore.removeOrderById(item.id);
    });
    
    // 从本地列表中删除 - 保留未确认的订单
    const unconfirmedItems = currentOrderList.value.filter(item => !item.isConfirmed);
    
    // 根据当前标签页更新对应的列表
    switch (active.value) {
        case 'all':
        // 删除全部  再更新为未确认订单列表  这样就不需要一个个找了  反而更方便
        orderList.allOrderList.splice(0, orderList.allOrderList.length, ...unconfirmedItems);
        break;
      case 'pending':
        orderList.pendingPaymentList.splice(0, orderList.pendingPaymentList.length, ...unconfirmedItems);
        break;
      case 'paid':
        orderList.finishedOrderList.splice(0, orderList.finishedOrderList.length, ...unconfirmedItems);
        break;
    }
    
    showToast('删除成功');
    isAllChecked.value = false;
  })
  .catch(() => {
    // 取消删除
  });
};

// 提交订单
const onSubmit = () => {
  if (confirmedOrders.value.length === 0) {
    showToast('请先选择订单');
    return;
  }

  showToast(`提交订单成功！共${confirmedOrders.value.length}个订单`);
  
  // 保存数据到orderStore的tempPaymentList
  orderStore.tempPaymentList.splice(0, orderStore.tempPaymentList.length, ...confirmedOrders.value);
  
  // 从原始列表中删除已提交的订单，避免重复添加
  confirmedOrders.value.forEach(item => {
    orderStore.removeOrderById(item.id);
  });
  
  // 同步更新本地列表
  switch (active.value) {
    case 'all':
      orderList.allOrderList = orderList.allOrderList.filter(order => !order.isConfirmed);
      break;
    case 'pending':
      orderList.pendingPaymentList = orderList.pendingPaymentList.filter(order => !order.isConfirmed);
      break;
    case 'paid':
      orderList.finishedOrderList = orderList.finishedOrderList.filter(order => !order.isConfirmed);
      break;
  }
  
  // 跳转到支付页面
  router.push('/payment');
};
</script>

<style scoped lang="scss">
.order-page {
  min-height: 100vh;
  background: #f6f6f6;
  display: flex;
  flex-direction: column;

  .order-content {
    flex: 1;
    padding: 12px;
    
    .order-list {
      margin-bottom: 80px; // 为底部操作栏留出空间
    }
  }

  .order-footer {
    background: #fff;
    border-top: 1px solid #ebedf0;

    .submit-bar {
      position: relative;
      .submit-bar-content {
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex: 1;

        .select-all-checkbox {
          font-size: 14px;
        }

        .delete-section {
          display: flex;
          align-items: center;
          margin-left: 16px;
          color: #969799;
          font-size: 14px;

          .delete-icon {
            margin-right: 4px;
          }
        }
      }

      .submit-tip {
        display: flex;
        align-items: center;
        font-size: 12px;
        color: #969799;
        padding: 8px 16px;
        background: #fff9ed;

        .tip-icon {
          margin-right: 4px;
          font-size: 14px;
        }
      }
    }
  }
}
:deep(.van-tabs__line) {
  background-color: #ffc400;
}
</style>
